#!/bin/bash

# =============================================================================
# 启动持续集成测试
# 根据不同结构发送不同邮件
# =============================================================================

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'


# NC重置日志颜色
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 获取工作空间路径（脚本所在的工作目录）
WORKSPACE=${WORKSPACE:-$(pwd)}
log_info "Jenkins工作空间: $WORKSPACE"

# 执行集成测试
run_integration_tests() {
    log_info "开始执行集成测试..."
    
    cd "$WORKSPACE"
    
    # 确保CI脚本有执行权限
    chmod +x "$WORKSPACE/depoy/ci/run_integration_tests.sh"
    
    # 执行CI脚本
    if bash depoy/ci/run_integration_tests.sh; then
        log_success "集成测试执行成功"
        return 0
    else
        log_error "集成测试执行失败"
        return 1
    fi
}

# 发送邮件通知
send_email_notification() {

    # 获取调用该函数的第一个参数（$1)
    local build_status=$1


    # 编号、构建URL、项目名称都是jeknins自动提供的内置环境变量
    local build_number=${BUILD_NUMBER:-"unknown"}
    
    # 构建Jenkins URL
    local jenkins_url=${JENKINS_URL:-"http://localhost:8080"}
    local job_name=${JOB_NAME:-"lottery-system"}
    local build_url=""
    
    if [ "$build_number" != "unknown" ]; then
        # 移除jenkins_url末尾的斜杠
        jenkins_url=${jenkins_url%/}
        build_url="${jenkins_url}/job/${job_name}/${build_number}"
    fi
    
    local console_log_file="$WORKSPACE/build_console.log"
    
    log_info "发送邮件通知 - 状态: $build_status"
    log_info "构建URL: $build_url"
    
    # 获取控制台日志的最后部分
    local console_log=""
    if [ -f "$console_log_file" ]; then
        console_log=$(tail -n 30 "$console_log_file" | head -c 800)
    fi
    
    cd "$WORKSPACE/integration-tests"
    
    # 使用Python发送邮件
    python3 -c "
import sys
import os

# 把当前目录添加到python的模块搜索路径
sys.path.append('.')

try:
    from emails.email_manage import EmailManage
    
    # 创建邮件管理器实例
    email_manager = EmailManage()
    
    # 发送构建通知
    success = email_manager.send_jenkins_build_notification(
        build_status='$build_status',
        build_number='$build_number',
        build_url='$build_url',
        console_log='''$console_log'''
    )
    
    if success:
        print('✅ 邮件通知发送成功')
        sys.exit(0)
    else:
        print('❌ 邮件通知发送失败')
        sys.exit(1)
        
except ImportError as e:
    print(f'❌ 导入邮件模块失败: {e}')
    sys.exit(1)
except Exception as e:
    print(f'❌ 发送邮件时出错: {e}')
    sys.exit(1)
"
    # 获取python3 -c返回的状态码 $?
    local email_result=$?
    if [ $email_result -eq 0 ]; then
        log_success "邮件通知发送成功"
    else
        log_error "邮件通知发送失败"
    fi
    
    return $email_result
}

# 主函数
main() {
    log_info "开始Jenkins集成测试执行..."
    
    # 运行集成测试
    log_info "运行集成测试..."
    if run_integration_tests; then
        log_success "集成测试执行成功（已满足通过率阈值）"
        send_email_notification "SUCCESS"
        exit 0
    else
        log_error "集成测试执行失败或未满足通过率阈值"
        send_email_notification "FAILURE"
        exit 1
    fi
    
    log_success "Jenkins集成测试完成"
}

# 显示帮助信息
# 直接执行主函数
main "$@"